package top.lanscarlos.ashcraft.repository;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Repository;
import top.lanscarlos.ashcraft.pojo.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Ashcraft
 * top.lanscarlos.ashcraft.repository
 *
 * @author Lanscarlos
 * @since 2022-05-30 17:47
 */
@Repository
public class OrderRepository {

    @Autowired
    private SessionFactory sessionFactory;

    @Autowired
    private Gson gson;

    /**
     * 查询订单
     * */
    @Nullable
    public Object query(int userId) {
        try (Session session = sessionFactory.openSession()) {
            User user = session.get(User.class, userId);
            if (user == null) return new ArrayList<>();
            return toJson(user.getOrders());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    /**
     * 购物车结算
     * */
    @Nullable
    public Order purchase(int userId) {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        try {
            User user = session.get(User.class, userId);
            if (user == null) return null;
            Cart cart = user.getCart();

            // 零钱不足
            if (user.getMoney() < cart.getTotalPrice()) return null;

            // 检查购物车是否为空
            List<CartItem> cartItems = cart.getItems();
            if (cartItems == null || cartItems.isEmpty()) return null;

            CartItem cartItem;
            OrderItem orderItem;
            List<OrderItem> orderItems = new ArrayList<>();

            for (int i=0; i<cartItems.size(); i++) {
                cartItem = cartItems.get(i);

                // 过滤未选择的项目
                if (!cartItem.isSelected()) continue;

                // 移除购物车子项
                cartItems.remove(cartItem);
                session.delete(cartItem);
                // i 自减
                i -= 1;

                orderItem = new OrderItem(cartItem);
                orderItems.add(orderItem);
                session.persist(orderItem);
            }

            // 没有购买任何商品
            if (orderItems.isEmpty()) return null;

            Order order = new Order(orderItems);
            // 扣除零钱
            user.setMoney(user.getMoney() - order.getTotalPrice());
            // 设置总价
            cart.setTotalPrice(0.0);
            user.getOrders().add(order);
            session.persist(order);
            session.update(cart);
            session.update(user);
            transaction.commit();
            return order;
        } catch (Exception e) {
            transaction.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
        return null;
    }

    public JsonElement toJsonTree(Object object) {
        return gson.toJsonTree(object);
    }

    public JsonElement toJson(Object object) {
        return toJsonTree(object);
    }
}
